--[[
使用注意事项
需要在某个nginx.conf里注册一个

init_worker_by_lua_block{
    local HttpUtil = require "http/http_util";  ---http util
    HttpUtil.init_dns_server(); --- 初始化 dns 服务
    local handle =nil;
    handle =function ()  ---创建一个定时任务
    local consulProperties = require "consul/consul_properties";
    consulProperties.get_properties_from_consul();
    ngx.timer.at(60,handle);
    end
    ngx.timer.at(60,handle);  ----每隔60秒去更新下consul的配置
}

需要在nginx.conf里增加一个 nginx.shared的配置项目 用于存储读取到的所有的配置文件
lua_shared_dict properties 5m;

依赖了 带dns 功能的http _util
]]--


local require = require
local PropertiesUtil = require("util/PropertiesUtil")
local HttpUtil = require("http/http_util")
 require("util/PrintUtil")
local cjson = require "cjson" ----引入cjson
local local_conf = require("core.config_local").local_conf()
local StringUtil= require("util.StringUtil")
local _M = {}
_M._VERSION="0.1"
local log = require("core.log")

ngx.log(ngx.INFO,"-------begin http consul-------")
function _M.get_properties_from_consul()
    get_properties_from_consul()
end
function get_properties_from_consul()  ----
    local http = require "resty.http"
    local httpc = http:new()
    --生产10.42.28.27


    local consul_host = local_conf.openresty.cloud.consul.host;

    local consul_port = local_conf.openresty.cloud.consul.port or 8500;

    --如果不是ip地址还要转换成ip地址
    if  not StringUtil.isIp(consul_host) then
        local realIp,domain =  HttpUtil:_get_addr(consul_host) --192.168.212.74
        if realIp ==nil then
            log.error("没有解析出consul的ip地址");
            return
        end
        consul_host = realIp;

    end
    --if(StringUtil)


    log.info("-------找到domain的值-------"..consul_host)
    local consul_config = local_conf.openresty.cloud.consul.config;
    print("cosul路径".."http://"..consul_host..":"..consul_port.."/v1/kv/config/"..consul_config["prefix"].."/"..consul_config["default-context"].."/"..consul_config["data-key"].."?dc=data-center-1")

    local resp,err = httpc:request_uri("http://"..consul_host..":"..consul_port.."/", ----请求http 接口

          {
        method = "GET",    ---请求方式
---             http://192.168.213.22:8500/v1/kv/config/smarthome/smarthome-app-srv/smarthome-app-srv-dev.yml?dc=data-center-1
        path="/v1/kv/config/"..consul_config["prefix"].."/"..consul_config["default-context"].."/"..consul_config["data-key"].."?dc=data-center-1",--consul上对应的服务名称 alpha是data-center-1
         headers = {
            ["Content-Type"] = "application/x-www-form-urlencoded",
        }
    })

    if not resp then
        log.error("请求consul 失败!!!!!!!!!!!!!!!")

        return
    end
    if not resp.body then
        log.error("请求consul 失败!!!!!!!!!!!!!!")

        return
    end
    resp=resp.body
    --log.info("请求consul 失败!!!!!!!!!!!!!!")
    log.info("请求http请求返回结果为"..resp)
    --ngx.log("请求http请求返回结果为"..cjson.encode(resp))
    --local resp = cjson.decode(resp);
    resp = cjson.decode(resp)  ---这里也可能因为consul的关系没有返回正确的值
    log.info("找到的结果cjson后数据类型是"..type(resp))

    local upstreams = {}
    for i, v in ipairs(resp) do
        log.info("找到的结果是["..tostring(i).."]value:"..type(v))
        --ngx.log(ngx.INFO,"找到的结果是["..tostring(i).."]value:"..v.key ..v.Value)
       -- ngx.say(v["Key"] ..ngx.decode_base64(v["Value"]))
       -- ngx.say("拿到的properties 是",ngx.decode_base64(v["Value"]))
        ----开始解析这个properties
        local propertiesStr =ngx.decode_base64(v["Value"]);---base64转码获取得到对应的配置str
        local properties = PropertiesUtil.parseProperties(propertiesStr); --将字符串解析到table


        --ngx.log(ngx.ERR,"find consul service address"..v.ServiceAddress)
        --upstreams[i] = {ip=v.ServiceAddress, port=3000}
        for k,v in pairs(properties) do  ---遍历这个table  然后把值放到 shared中
            if type(v) == "string" then
                ngx.shared.properties:set(k, v)
            --放到整个的shared dict 字典里
              local_conf[k]=v;
            end
        end

        printTable(local_conf,4);--打印table
    end
    --ngx.shared.upstream_list:set("api_list", cjson.encode(upstreams))
end
--
function _M.init_worker()
    print("启动定时任务  读取consul配置")
    ngx.timer.at(0,get_properties_from_consul)
end
return _M
